package com.example.workflow.service;

import com.example.workflow.dto.ProcessDeployRequest;
import com.example.workflow.dto.SystemRequest;
import com.example.workflow.entity.SysProcess;
import com.example.workflow.entity.SysSystem;
import com.example.workflow.mapper.SysProcessMapper;
import com.example.workflow.mapper.SysSystemMapper;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class SystemService {

    @Autowired
    private SysSystemMapper systemMapper;
    
    @Autowired
    private SysProcessMapper processMapper;
    
    @Autowired
    private RepositoryService repositoryService;
    
    @Autowired
    private RuntimeService runtimeService;

    @Transactional
    public void saveSystem(SystemRequest request) {
        SysSystem system = new SysSystem();
        BeanUtils.copyProperties(request, system);
        if (system.getId() == null) {
            systemMapper.insert(system);
        } else {
            systemMapper.update(system);
        }
    }

    public List<SysSystem> getSystemList() {
        return systemMapper.findAll();
    }



    @Transactional
    public void deployProcess(ProcessDeployRequest request) throws IOException {
        // 部署流程
        Deployment deployment = repositoryService.createDeployment()
                .addInputStream(request.getFile().getOriginalFilename(), request.getFile().getInputStream())
                .name(request.getProcessName())
                .deploy();

        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();

        // 保存流程信息
        SysProcess process = new SysProcess();
        process.setSystemId(request.getSystemId());
        process.setProcessKey(request.getProcessKey());
        process.setProcessName(request.getProcessName());
        process.setDescription(request.getDescription());
        process.setVersion(processDefinition.getVersion());
        processMapper.insert(process);
    }

    public List<ProcessInstance> getRunningProcesses(String processKey) {
        return runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(processKey)
                .active()
                .list();
    }

    public void deleteSystem(Long systemId) {
        systemMapper.deleteById(systemId);
    }
} 